﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lails.Config
{
    public class ConfigServer<T>
    {
        public string Path { get; private set; }
        public T Data { get; set; }
        private System.Timers.Timer _timer;
        public event EventHandler ConfigChanged;
        protected virtual void OnConfigChanged()
        {
            if (ConfigChanged != null)
            {
                ConfigChanged(this, null);
            }
        }

        public ConfigServer(string path, int autoChangeSecond)
        {
            this.Path = path;
            Load();
            if (autoChangeSecond > 0)
            {
                _timer = new System.Timers.Timer(1000 * autoChangeSecond);
                _timer.Elapsed += _timer_Elapsed;
                _timer.Start();
            }
        }

        public void Load()
        {
            this.Data = ConfigLoader.Load<T>(Path);
        }

        private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //采用Json序列化的方式，对比前后配置文件是否发生变化
            string curJson = JsonConvert.SerializeObject(Data);
            var newConfig = ConfigLoader.Load<T>(Path);
            string newJson = JsonConvert.SerializeObject(newConfig);
            bool isChanged = (curJson != newJson);
            if (isChanged)
            {
                Data = newConfig;
                OnConfigChanged();
            }
        }

    }
}
